﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using MiniStock.Infrastructure.Queue;
using Microsoft.Practices.Unity;

namespace MiniStock.Infrastructure.Configurator
{
    public class EventProcessorDescriptor
    {
        public string EventProcessorName { get; set; }
        public IEventQueue Queue { get; set; }
        public List<string> Plugins { get; set; }
        public int WorkerThreadCount { get; set; }
        public bool IsProcessorNode { get; set; }

        public List<Type> PluginTypes;

        private void AssertPluginTypes()
        {
            if (PluginTypes != null || !IsProcessorNode)
                return;

            PluginTypes = new List<Type>();
            foreach(var s in Plugins)
            {
                var t = Type.GetType(s);
                if(t != null)
                {
                    var plugin = Activator.CreateInstance(t) as IProcessorPluginEntryPoint;
                    if(plugin == null)
                        throw new ApplicationException("Plugin type cannot be instantiated: " + t.Name);
                    PluginTypes.AddRange(plugin.EntityRootTypes);
                }
            }
        }

        public bool IsApplicableFor(string entityHash)
        {
            Debug.Assert(IsProcessorNode, "IsApplicableFor should not be used on persister nodes");

            AssertPluginTypes();
            return PluginTypes.Any(i => entityHash.StartsWith(i.Name));
        }

    }
}
